package com.enthal.basicpers

import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import android.widget.Toast


// https://blog.csdn.net/qq_38520096/article/details/79007228
class GuardService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Toast.makeText(applicationContext, "GuardService Listener Start Command",
            Toast.LENGTH_LONG).show()
        Log.i("Notice"," GuardService Listener Start Command")

        val boundnotice = RuntimeStatus.buildNotice(applicationContext,
            "AstroAppGuard","请确保此通知一直存在" )
        startForeground(2, boundnotice)

        //绑定建立链接
        bindService(
            Intent(applicationContext, NoticeListenerService::class.java),
            connection, Context.BIND_IMPORTANT)
        return START_STICKY
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        stopForeground(true)
        unbindService(connection)

        super.onDestroy()
    }

    //创建一个ServiceConnection回调，通过IBinder进行交互
    // https://www.jianshu.com/p/9d5d988891d7
    private val connection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            //本句话借用：Android系统在同service的连接意外丢失时调用这个．
            // 比如当service崩溃了或被强杀了．当客户端解除绑定时，这个方法不会被调用．
            Log.e("ServiceStatus", "DisConnected: $name")

            //断开链接
            startService(Intent(applicationContext, NoticeListenerService::class.java))
            //重新绑定
            bindService(Intent(applicationContext, NoticeListenerService::class.java),
                this, Context.BIND_IMPORTANT)
        }

        override fun onServiceConnected(name: ComponentName?, iBinder: IBinder?) {
            Log.i("ServiceStatus", "Connected: $name")

            //下面是通过代理的方式将iBinder转成IMyAidlInterface
            val myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder)

        }
    }
}
